<?php
declare (strict_types=1);

namespace ciphertext;

/**
 * 系统密码RSA加解密
 */
class RsaPassword
{
    //公钥
    public static string $publicKey = '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzGViQVk+9F42Khrr71EP
yKHQjApzjqqWP4OLTlHdg+S9kG6yZe7lF3r1CRYsNGB9Un/7A4fJvwZxrYhYZeEE
5ETAhUEqOMTUNw1hqGviJBFI1uJcCKgJm0QKJHB/xfl8xhqUPEYgJbwFwvEnOG84
+qwUZh3nY2r677/5yqo/rrwW/Sb06AN6+sA2iXZ5UC3F734gCnfC3LzlPFqC3jrl
h0tstz8G6H1AN3F684WNZYME7sQh6irBpxPV+rO3cR6yzD3J042MX2si2RuHMP06
R8SXk7linKui5UHOz7lUjtKIdTrEIys0VOCfbADrY4TCKM3v5ewXezR8kXfS9g1G
PQIDAQAB
-----END PUBLIC KEY-----';

    //私钥
    private static string $privateKey = '-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDMZWJBWT70XjYq
GuvvUQ/IodCMCnOOqpY/g4tOUd2D5L2QbrJl7uUXevUJFiw0YH1Sf/sDh8m/BnGt
iFhl4QTkRMCFQSo4xNQ3DWGoa+IkEUjW4lwIqAmbRAokcH/F+XzGGpQ8RiAlvAXC
8Sc4bzj6rBRmHedjavrvv/nKqj+uvBb9JvToA3r6wDaJdnlQLcXvfiAKd8LcvOU8
WoLeOuWHS2y3PwbofUA3cXrzhY1lgwTuxCHqKsGnE9X6s7dxHrLMPcnTjYxfayLZ
G4cw/TpHxJeTuWKcq6LlQc7PuVSO0oh1OsQjKzRU4J9sAOtjhMIoze/l7Bd7NHyR
d9L2DUY9AgMBAAECggEAGZIpe7F1nc7Xieb6U2NZzSjpVUvNbzDKQUHswKyfQOvy
B0rCCNydTpW0aCGdACR+KT8XoTZwt/RPbn1bScuf+Ard5w3jAV0mi4iiChcNIKQE
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15dARqdTS3433Zs1S42CDD1Hd
YuzAfn1ZK2PFULWp/T8MfCc=
-----END PRIVATE KEY-----';

    /**
     * 使用公钥加密
     * @param string $data
     * @return false|string
     */
    public static function publicEncrypt(string $data): bool|string
    {
        //公钥加密
        //第一个参数是待加密的数据只能是string，第二个参数是加密后的数据
        $return_en = openssl_public_encrypt($data, $crypted, self::$publicKey);
        if (!$return_en) {
            return false;
        }
        return base64_encode($crypted);
    }

    /**
     * 使用公钥解密
     * @param string $data
     * @return false|mixed
     */
    public static function publicDecrypt(string $data): mixed
    {
        $return_de = openssl_public_decrypt(base64_decode($data), $decrypted, self::$publicKey);
        if (!$return_de) {
            return false;
        }
        return $decrypted;
    }

    /**
     * 使用私钥加密
     * @param string $data
     * @return false|string
     */
    public static function privateEncrypt(string $data): bool|string
    {
        //公钥加密
        //第一个参数是待加密的数据只能是string，第二个参数是加密后的数据
        $return_en = openssl_private_encrypt($data, $crypted, self::$privateKey);
        if (!$return_en) {
            return false;
        }
        return base64_encode($crypted);
    }

    /**
     * 使用私钥解密
     * @param string $data
     * @return mixed
     */
    public static function privateDecrypt(string $data): mixed
    {
        $return_de = openssl_private_decrypt(base64_decode($data), $decrypted, self::$privateKey);
        if (!$return_de) {
            return false;
        }
        return $decrypted;
    }

}
